﻿using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using SingleUserMall.Common;
using SingleUserMall.Workers.Form;
using SingleUserMall.Workers.VO;
using System.Linq;
using System.Threading.Tasks;

namespace SingleUserMall.Workers
{
    [AbpAuthorize]
    public class WorkerManageAppService : SingleUserMallAppServiceBase, IWorkerManageAppService
    {
        private readonly IRepository<Worker,long> _workerRepository;
        public WorkerManageAppService(IRepository<Worker,long> workerRepository)
        {
            _workerRepository = workerRepository;
        }
        public async Task<WorkerViewVO> GetWorkerAsync(SingleId<long> form)
        {
            var worker = await _workerRepository.FirstOrDefaultAsync(form.Id);
            return worker.ToVO<Worker, WorkerViewVO>((w, vo) =>
            {
            });
        }

        public async Task<PagedResultDto<WorkerViewVO>> GetWorkersBySearchAsync(WorkerSearchForm form)
        {
            var query = _workerRepository.GetAll()
                .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.Name.Contains(form.Keywords))
                .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Worker, WorkerViewVO>(form,(w,vo)=>
            {
                vo.FeedbackRate = w.WorkerStar * 20 + "%";
            });
        }

        public async Task SaveWorkerAsync(WorkerForm form)
        {
            var worker = await _workerRepository.FirstOrDefaultAsync(form.Id);
            if (worker != null)
            {
                worker = form.MapTo(worker);
                await _workerRepository.UpdateAsync(worker);
            }
            else
            {
                worker = form.MapTo<Worker>();
                worker.WorkerStar = 5;
                await _workerRepository.InsertAsync(worker);
            }
        }

        public async Task RemoveAsync(SingleId<long> form)
        {
            await _workerRepository.DeleteAsync(form.Id);
        }
    }
}
